import React, { memo, useState, useEffect } from "react";
import css from './css.module.scss'
import { Upload, message, Progress } from 'antd';
import { useSelector, shallowEqual, useDispatch, } from "react-redux";
import { UploadOutlined, } from '@ant-design/icons';
import { ossUploadEntryFile, uploadFile } from '../../services/home'
import { getDetailsAction } from "../home/store/actionCreators";
export default memo(function RechTitle(props) {
    const { details } = useSelector(
        (state) => ({
            details: state.getIn(["home", "details"]),
        }),
        shallowEqual
    );

    const dispatch = useDispatch();
    useEffect(() => {
        dispatch(getDetailsAction());
    }, [dispatch]);
    const { Dragger } = Upload;
    const [fileList, setFileList] = useState([])
    const [percent, setPercent] = useState(0)
    const [isSucc, setIsSucc] = useState(false)
    const props2 = {
        name: 'file',
        multiple: true,
        // showUploadList: true,/
        action: 'https://cbda-default-bucket.oss-cn-beijing.aliyuncs.com',
        onRemove: file => {
            const index = fileList.indexOf(file);
            const newFileList = fileList.slice();
            newFileList.splice(index, 1);
            setFileList(newFileList)
        },
        // onChange(info) {
        //     const event = info.event
        //     console.log(info, '进度条数值')
        //     if (event) { // 一定要加判断，不然会报错
        //         let percent = Math.floor((event.loaded / event.total) * 100)
        //         setPercent(percent)
        //         console.log(percent, '进度条数值') // percent就是进度条的数值
        //     }
        // },
        beforeUpload: file => {
            setFileList([...fileList, file])
            return false;
        },
        fileList,
    };
    //确定上传
    const handleUpload = () => {
        if (fileList.length === 0) {
            message.info(`请点击上传文件!`);
            return
        }
        if (isSucc) {
            message.info('上传中,请勿重复点击');
            return
        }
        fileList.forEach(async item => {
            //获取oss参数

            const oss = await ossUploadEntryFile({ fileName: item.name, customizeId: 2 })
            let fileData = {
                ...oss.data,
                file: item,
            }
            const formData = new FormData();
            if (fileData) {
                Object.keys(fileData).forEach(key => {
                    formData.append(key, fileData[key]);
                });
            }
            //上传
            try {
                //第二个参数为 上传进度
                await uploadFile(formData, (progressEvent) => {
                    const complete = (progressEvent.loaded / progressEvent.total * 100 | 0);
                    // file.percent = complete;
                    setIsSucc(true)
                    setPercent(complete)
                    if (complete == 100) {
                        setIsSucc(false)
                    }
                    console.log(complete, '上传进度数值...')
                })
                message.success(`上传成功!`);
                setFileList([])
            } catch (error) {
                setIsSucc(false)
                message.error(`上传失败!`);
            }

        })

    }
    //修改fileList 需要在useEffect内监听
    useEffect(() => {

        // console.log(fileList, '文件列表')
    }, [fileList])
    useEffect(() => {
        // console.log(fileList, 'oss')
    }, [fileList])
    return (
        <div >
            <div className='w' style={{ margin: '60px auto' }}>
                <div className={css.upload_box}>
                    <Dragger {...props2}>
                        <p className="ant-upload-drag-icon">
                            <UploadOutlined />
                        </p>
                        <p className="ant-upload-text">将文件拖到此处，或 点击上传</p>
                        {/* <p className="ant-upload-hint">
                            Support for a single or bulk upload. Strictly prohibit from uploading company data or other
                            band files
                    </p> */}
                    </Dragger>
                </div>

            </div>
            <div style={{ textAlign: 'center', marginTop: '7px' }} dangerouslySetInnerHTML={{ __html: details.uploadTip }}>
            </div>
            {fileList.length !== 0 && <div style={{ width: '800px', margin: '0 auto', marginTop: '20px' }}><Progress status="active" trailColor='#999' percent={percent} /></div>}
            <div onClick={e => handleUpload()} className={css.btn}>
                确认上传
            </div>
        </div >
    )
})
